package cn.edu.gzist.chapter08kafka.kafkaclient;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.time.Duration;
import java.util.Collections;
import java.util.Properties;

public class KafkaConsumerMain {
    public static void main(String[] args) {
        // 1. 配置 Kafka 连接、反序列化、消费者组等参数
        Properties props = new Properties();
        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); // Kafka 集群地址 bootstrap.servers
        props.put(ConsumerConfig.GROUP_ID_CONFIG, "test_group"); // 消费者组 ID，同一组内消费者协调消费 group.id
        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); // 键的反序列化器 key.deserializer org.apache.kafka.common.serialization.StringDeserializer
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); // 值的反序列化器 value.deserializer org.apache.kafka.common.serialization.StringDeserializer
        props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); // 没有已提交偏移量时，从最早消息开始消费 auto.offset.reset earliest(从头开始消费)/latest/none

        // 2. 创建 Consumer 实例
        KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);

        // 3. 订阅主题
        String topic = "test_topic";
        consumer.subscribe(Collections.singletonList(topic));

        // 4. 循环拉取消息（长轮询）
        try {
            while (true) {
                ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100));
                for (ConsumerRecord<String, String> record : records) {
                    System.out.printf("收到消息：主题=%s，分区=%d，偏移量=%d，键=%s，值=%s%n",
                            record.topic(), record.partition(), record.offset(),
                            record.key(), record.value());
                }
                // 手动提交偏移量（也可配置自动提交，生产环境建议手动更可靠）
                consumer.commitSync();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 5. 关闭 Consumer
            consumer.close();
        }

    }
}
